<?php

namespace App\Traits;

use App\Constants\AuthType;
use App\Exceptions\ApiException;
use App\Models\User;
use App\Services\Base\CacheService;

trait BaseTrait
{

    public function error($code, $msg = "")
    {
        if (is_numeric($code) && $code > M_START && $code <= M_END) {
            throw new ApiException($msg, $code);
        } else {
            throw new ApiException('', 405); //code必须为数字
        }
    }

    public function paramsExist($param, $data)
    {
        foreach ($param as $k => $v) {
            if (!array_key_exists($v, $data)) {
                throw new ApiException("($v)", 408);
            }
        }
    }

    public function paramsEmpty($param, $data)
    {
        foreach ($param as $k => $v) {
            if (!$data[$v]) {
                throw new ApiException("($v)", 410);
            }
        }
    }

    public function setInfo(User $user)
    {
        $info = [
            'id' => $user->id,
            'name' => $user->name,
            'nickname' => $user->nickname,
            'phone' => $user->phone,
            'email' => $user->email,
            'register_type' => $user->register_type,
            'rid' => $user->rid,
            'avatar' => $user->avatar,
            'created_at' => strtotime($user->created_at),
            'default_avatar' => g_app_image($user['avatar'] ?? "/user.jpg")
        ];

        CacheService::hSet(R_USER_INFO, $user->id, $info, true);
    }

    public function getInfo($uid, $unset = true)
    {
        $user = CacheService::hGet(R_USER_INFO, $uid, true);
        if ($user) {
            if ($unset) {
                unset($user['id']);
            }
        }
        return $user;
    }

    public function getNameAvatar($uid, $phone = false)
    {
        $user = CacheService::hGet(R_USER_INFO, $uid, true);
        $new_result = ['avatar' => "", "name" => "未知"];
        if ($user) {
            $new_result['avatar'] = g_app_image($user['avatar'] ?? "/user.jpg");
            $name = $user['nickname']
                ?: ($user['register_type'] == AuthType::CHECK_EMAIL ? $user['email'] : $user['phone'])
                    ?: $user['name'];

            $new_result['name'] = g_str_encrypt($name, 2, 2, 2);
            $new_result['id'] = $uid;
            $new_result['created_at'] = $user['created_at'];
            if ($phone) {
                $new_result['phone'] = $user['phone'];
            } else {
                $new_result['phone'] = "";
            }
        }
        return $new_result;
    }
}
